var bmap = require('../../../libs/bmap_wx/bmap-wx.min.js');

var wxMarkerData = [];  //定位成功回调对象  
var BMap;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ak: "cAfvdwFgojWCjp5GD2xEzKDmDlXZCUl6", //填写申请到的ak 
    suggestionCity: '',//搜索的范围城市
    showList: false, //是否显示列表
    list_suggestionResult: [], //suggestion结果集
    // whichPage: 1,//1：表示选择发货地 2：表示选择收货地
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    that.setData({
      suggestionCity: options.suggestionCity,
    });

    // 新建bmap对象   
    BMap = new bmap.BMapWX({
      ak: that.data.ak
    });
  },

  /**
   * input字符变化的监听
   */
  valueChange: function (e) {
    var that = this;
    //如果数据为空
    if (e.detail.value === '') {
      that.setData({
        showList: false,
      });
      return;
    }

    //请求失败
    var fail = function (data) {
      // console.log(data);
      that.setData({
        showList: false,
      });
    };

    //请求成功
    var success = function (data) {
      // var sugData = '';
      console.log(data);

      that.setData({
        list_suggestionResult: data.result,
        showList: 'ok' == data.message ? true : false,
      });
    }

    BMap.suggestion({
      query: e.detail.value,
      region: that.data.suggestionCity,
      city_limit: true,
      fail: fail,
      success: success
    });
  },

  click_item: function (e) {
    var that = this;

    var pos_click = e.currentTarget.dataset.id;

    //在返回上一个页面时，将数据回传回去
    var list_suggestionResult = that.data.list_suggestionResult;
    var suggestionResult = list_suggestionResult[pos_click]
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面

    prevPage.setData({
      address: suggestionResult.name,
      // address: suggestionResult.name + '(' + suggestionResult.city + ' ' + suggestionResult.district + ')',
      gps_lat: suggestionResult.location.lat,
      gps_lon: suggestionResult.location.lon,
    });

    //返回上一个页面
    wx.navigateBack();
  },
})